package com.ali.service.impl;

import com.ali.common.BeanCopyUtil;
import com.ali.config.JWTUtil;
import com.ali.dao.UserLoginMapper;
import com.ali.dao.UserMapper;
import com.ali.dto.PageInfo;
import com.ali.dto.UserInfo;
import com.ali.dto.UserLoginInfo;
import com.ali.entity.User;
import com.ali.entity.UserLogin;
import com.ali.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserLoginMapper userLoginMapper;

    @Override
    public UserInfo login(String username, String password) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new RuntimeException("根据用户名未查询到用户");
        }

        userInfo.setName(user.getName());

        String token = JWTUtil.getToken(username, 24 * 60 * 60);
        //TODOredis存入token，时间为1小时

        userInfo.setToken(token);

        saveUserLogin(username);

        return userInfo;
    }

    /**
     * 保存用户登录日志
     */
    private void saveUserLogin(String username) {
        UserLogin userLogin = new UserLogin();
        userLogin.setUsername(username);
        userLoginMapper.insert(userLogin);
    }

    @Override
    public void logout(String username) {
        //TODOredis清除token
    }

    @Override
    public PageInfo<UserLoginInfo> queryLoginRecord(String pageNo, String pageSize) {
        PageInfo<UserLoginInfo> pageInfo = new PageInfo<>();
        pageInfo.setPageNo(pageNo);
        pageInfo.setPageSize(pageSize);

        Page<UserLogin> page = new Page<>(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        QueryWrapper<UserLogin> queryWrapper = new QueryWrapper<>();
        Page<UserLogin> resultPage = userLoginMapper.selectPage(page, queryWrapper);
        List<UserLogin> userLogins = resultPage.getRecords();
        List<UserLoginInfo> userLoginInfos = BeanCopyUtil.copyListProperties(userLogins, UserLoginInfo::new);

        pageInfo.setTotal(String.valueOf(resultPage.getTotal()));
        pageInfo.setData(userLoginInfos);
        return pageInfo;
    }
}